package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.BindFamilyDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.zzyl.nursing.service.IWeChatService;
import com.zzyl.nursing.vo.BindElderDeviceVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.MyFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zzyl.common.utils.PageUtils.startPage;

/**
 * 老人家属Service业务层处理
 * 
 * @author ljc
 * @date 2025-03-03
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private IWeChatService weChatService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        LoginVo loginVo = new LoginVo();
        // 获取openId
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        //查询数据库判断客户是否存在
        if (ObjectUtil.isEmpty(openId)){
           throw  new BaseException("获取openId失败");
        }
        //查询用户是否存在
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openId);
        FamilyMember familyMember = this.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(familyMember)){
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }
        //获取手机号
        String phoneNumber = weChatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        saveOrUpdateFamilyMember(familyMember,phoneNumber);
        //生成token
        Map<String, Object> cliams = new HashMap<>();
        cliams.put( "id", familyMember.getId());
        cliams.put( "nickName", familyMember.getName());

        String token = tokenService.createToken(cliams);
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }

    /**
     *  保存或更新
     * @param familyMember
     * @param phoneNumber
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember, String phoneNumber) {
        //判断电话是否存在
        if (!ObjectUtil.equals(phoneNumber, familyMember.getPhone())){
            familyMember.setPhone(phoneNumber);
        }
        if (ObjectUtil.isNotEmpty(familyMember.getId())){
            //更新
            updateById(familyMember);
            return;
        }
        //新增员工
        //随机获取一盒集合的下标
        int index = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(index)+StrUtil.sub(phoneNumber,7,11));
        save(familyMember);


    }


    /**
     * 绑定家人
     * @param bindFamilyDto
     */
    @Override
    public void bingFamily(BindFamilyDto bindFamilyDto) {
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        //从ThradLocal中获取用户id
        Long userId = UserThreadLocal.get();
        familyMemberElder.setFamilyMemberId(userId);
        //判断绑定的老人是否存在
        if (ObjectUtil.isEmpty(bindFamilyDto.getIdCard()) && ObjectUtil.isEmpty(bindFamilyDto.getName())){
            throw new BaseException("绑定老人姓名或身份证信息不能为空");
        }
        //从数据库中查询
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, bindFamilyDto.getIdCard())
                .eq(Elder::getName, bindFamilyDto.getName()).one();
        if (ObjectUtil.isEmpty(elder)){
            throw new BaseException("绑定老人不存在,或者姓名和身份证号错误");
        }
        //是否重复绑定
        /*LambdaQueryWrapper<FamilyMemberElder> condition = new LambdaQueryWrapper<>();
        condition.eq(FamilyMemberElder::getElderId, elder.getId())
                .eq(FamilyMemberElder::getFamilyMemberId, userId);
        if (ObjectUtil.isNotNull(condition)){
            throw new BaseException("该老人已被绑定");
        }*/
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setRemark(bindFamilyDto.getRemark());
        //保存数据
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 查询家人列表
     *
     * @return
     */
    @Override
    public List<MyFamilyVo> myFamily() {
        Long userId = UserThreadLocal.get();
         return familyMemberElderMapper.selectMyFamily(userId);
    }

    /**
     * 查看已绑定家人列表（分页查询）
     * @param
     * @return
     */
    @Override
    public List<BindElderDeviceVo> queryPage() {
        startPage();
        Long memberId = UserThreadLocal.get();
        return familyMemberElderMapper.queryPage(memberId);
    }
}
